<template>
  <el-row>
    <el-col :span="24">
      <Portlet>
        <table class="order-table">
          <tr v-for="(item, index) in tableData" :key="index">
            <td class="order-table-td">
              <table class="order-table-td-table">
                <tr class="tr-header">
                  <td width="30%" align="left" colspan="2">
                    订单号：<a @click="show(item)" >{{item.orderNo}}</a>
                    <span style="margin-left:10px;"><mark-template :id="item.id" :resultColor="item.colorFlag ? item.colorFlag : 'gray'" @refresh="refresh"></mark-template></span>
                  </td>
                  <td width="20%" align="left">
                    服务方：{{item.serviceProvider}} （ {{item.serviceProviderPhone}} ）
                  </td>
                  <td width="25%" align="center">
                    {{item.business}} | {{item.service}}：<span class="font-orange font-weight500">{{item.orderState | filterDataBaseDictionary}}</span>
                  </td>
                  <td width="25%" align="center">
                    下单时间：{{item.foundTime}}
                  </td>
                </tr>
                <tr class="tr-body">
                  <td>
                    <Upload-image :listItemStyle="listItemStyle" :showPictureNum="true" :readonly="true" :value="handleJsonStringArr(item.imgAddress)"></Upload-image>
                  </td>
                  <td>
                    <div>
                      <div class="marginBottom8">
                        商品名称：<truncate :value="item.goodsName" :maxLength="10"></truncate>
                      </div>
                      <div class="marginBottom8">
                        商品数量：{{item.goodsSum}}套
                      </div>
                    </div>
                    <div class="clearfix"></div>
                  </td>
                  <td>
                    <div class="marginBottom8">
                      客户姓名：{{item.consigneeName}} {{item.consigneePhone}}
                    </div>
                    <div class="marginBottom8">
                      客户地址：<truncate :value="item.consigneeProvince + item.consigneeCity + item.consigneeDistrict + item.consigneeAddress" :maxLength="24"></truncate>
                    </div>
                  </td>
                  <td align="center">
                    <div class="marginBottom8">
                      <span class="font-red font-weight500" style="font-size: 24px;">￥{{item.payMoneyTotal}}</span>
                    </div>
                    <div class="marginBottom8">
                      应付总额
                    </div>
                  </td>
                  <td align="center">
                    剩余支付：{{item.payTime | filterDayHours}}
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </Portlet>
    </el-col>
    <el-col :span="24">
      <Portlet title="支付方式" :show-title="true">
        <el-form :model="model" ref="form">
          <el-col :span="24" style="text-align: left;">
            <el-form-item
              prop="paymentType"
              :rules="[{required: true, message:'支付方式必须', trigger: 'change'}]"
            >
              <el-radio-group class="el-radio-button-background-color-transparent" v-model="model.paymentType" >
                <el-tooltip :key="index"  v-for="(item, index) in computedPaymentTypes" :disabled="!item.tip" :content='item.tip'>
                  <el-radio-button :label="item.value" :disabled="item.disabled">
                    <img :src="item.disabled ? item.iconDis : item.icon" style="width: 80px; height: 30px;"/>
                  </el-radio-button>
                </el-tooltip>
              </el-radio-group>
              <span style="margin-left: 20px;">余额：{{balance | decimalNumFilter}} 元</span>
            </el-form-item>
            <div></div>
          </el-col>
        </el-form>
        <div class="clearfix"></div>
      </Portlet>
    </el-col>
    <el-col :span="24" class="div-payment-buttom-button">
      <table style="width: 100%;">
        <tr>
          <th width="65%" align="right">
            <span>应付金额：<span class="font-red">￥{{lastMoney}}</span> </span>
          </th>
          <th width="120px" align="center">
            <div style="margin: 0 15px 0 15px;">
              <el-button type="primary" :loading="btnLoading" @click.prevent="payment($event)">确认支付</el-button>
            </div>
          </th>
        </tr>
      </table>
    </el-col>
    <el-col :span="24">
      <span class="font-red">支付说明：请在确认支付后24小时内完成订单支付，逾期未完成订单将自动回退至暂存单中</span>
    </el-col>
    <el-dialog
      title="温馨提示"
      :visible.sync="paymentState"
      width="30%"
      center
    >
      <div style="text-align:center">恭喜您支付成功！本页面即将在3秒后跳转待付款列表</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnDialog">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible.sync="payDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      center
    >
      <div style="text-align:center" v-if="!disabledBtn">请您在新打开的页面完成支付?</div>
      <div style="text-align:center" v-if="disabledBtn">
        <b style="font-size: 16px;">订单支付状态暂时无法确认</b>
        <p>尊敬的客户你好，很抱歉我们暂时无法确认您的支付结果,<br>
          建议您等待五分钟后再查看支付结果</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!disabledBtn" @click="unsuccessful">支付遇到问题</el-button>
        <el-button type="primary" v-if="!disabledBtn" @click="successful" :disabled="disabledBtn">{{ disabledBtn ? '等待支付结果' : '已经完成支付' }}</el-button>
        <el-button type="primary" v-if="disabledBtn" @click="btnDialog"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="钱包密码"
      :visible.sync="showWalletPay"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
      center
    >
      <div style="text-align: center">
        <el-input v-model="walletPwd" type="password" :maxlength="6" />
        <span class="font-red">{{error_message}}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWalletPay = false">取 消</el-button>
        <el-button type="primary" @click="walletpay" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <div v-html="htmltext"></div>
  </el-row>
</template>
<script>
import {arrayColumn, dotData, copy, confirm, handleJsonStringArr, alert} from '@/utils'
import {unixTimestampFilter, filterDayHours, decimalNumFilter} from '@/filters'
import {payFhbTypes} from '@/utils/selectOptions'
import {mapGetters} from 'vuex'
import markTemplate from '@/components/markTemplate'
export default {
  name: 'detailBatchPayment',
  components: {
    markTemplate
  },
  data() {
    return {
      listItemStyle: {
        width: '120px',
        height: '90px'
      },
      ids: [],
      tableData: [],
      paymentTypes: [],
      model: {
        paymentType: ''
      },
      htmltext: '',
      params: {
        pageSize: 20,
        pageNum: 1,
        orderNo: this.$route.params.ids
      },
      paymentState: false,
      payDialog: false,
      disabledBtn: false,
      timer: 3000,
      btnLoading: false,
      balance: 0,
      showWalletPay: false,
      walletPwd: '',
      error_message: '',
      loading: false,
      tempArr: []
    }
  },
  watch: {
    'walletPwd'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.error_message = ''
      if (this.loadding) {
        this.loadding = false
      }
    },
    'lastMoney'(val, oldVal) {
      if (val === 0) {
        this.model.paymentType = '3'
      }
    }
  },
  filters: {
    unixTimestampFilter,
    filterDayHours,
    decimalNumFilter
  },
  created() {
    // 支付方式
    this.createPaymentTypes()
    this.httpGetTableData()
    // 获取钱包余额
    this.$ajax.get('/ms-user-wallet/wallet/home-page').then(response => {
      let success = dotData(response, 'success')
      if (success) {
        this.balance = dotData(response, 'data.balance')
      }
    })
  },
  computed: {
    cantWalletPay: function() {
      if (this.balance < this.lastMoney) {
        return true
      } else {
        return false
      }
    },
    usedArr: function() {
      let tempArr = []
      this.tableData.forEach(v => {
        if (v.couponsId) {
          tempArr.push(v.couponsId)
        }
      })
      return tempArr
    },
    totalMoney: function() {
      let totalMoney = 0
      this.tableData.forEach(v => {
        totalMoney += Number(v.payMoneyTotal) || 0
      })
      return decimalNumFilter(totalMoney)
    },
    totalCoupons: function() {
      let totalCoupons = 0
      this.tableData.forEach(v => {
        if (v.couponsId) {
          let coupons = v.fhbCoupons.find(cou => cou.id === v.couponsId)
          console.log(coupons)
          totalCoupons += Number(coupons.discount)
        }
      })
      return decimalNumFilter(totalCoupons)
    },
    lastMoney: function() {
      let lastMoney = this.totalMoney - this.totalCoupons
      return decimalNumFilter(lastMoney)
    },
    computedPaymentTypes() {
      return this.paymentTypes.map(v => {
        v = Object.assign({}, v)
        // 余额为零 禁用 支付宝微信
        if (this.lastMoney === 0) {
          if (['1', '2'].indexOf(v.value) >= 0) {
            v.disabled = true
          }
        }
        // 余额不足 禁用钱包余额
        if (this.cantWalletPay) {
          if (v.value === '3') {
            v.disabled = true
          }
        }

        // 配置禁用支付宝
        if (this.GET_GLOBAL_CONFIG('aliPayPC') === false) {
          console.log('aliPayPC', v.value)
          if (v.value === '1') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 配置禁用微信
        if (this.GET_GLOBAL_CONFIG('weChatPayPC') === false) {
          if (v.value === '2') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 配置禁用钱包余额
        if (this.GET_GLOBAL_CONFIG('walletPC') === false) {
          if (v.value === '3') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        return v
      })
    },
    ...mapGetters(['GET_GLOBAL_CONFIG'])
  },
  methods: {
    handleJsonStringArr,
    refresh() {
      this.httpGetTableData()
    },
    createPaymentTypes() {
      payFhbTypes().then(arr => {
        this.paymentTypes = arr
      })
    },
    handleChange(item) {
    },
    httpGetTableData() {
      this.$ajax.get('/ms-fahuobao-json-view/FhbOrder/findFhbOrderByNo', this.params).then(response => {
        this.tableData = copy(response.data, true)
        this.tableData.forEach(item => {
          item.imgAddress = handleJsonStringArr(item.imgAddress)
          let obj = item.fhbCoupons.find(v => v.isDefault === 1) || {}
          this.$set(item, 'couponsId', obj.id)
        })
        this.ids = arrayColumn(response.data, 'id')
      })
    },
    payment($event) {
      if (!this.model.paymentType) {
        alert('请选择支付方式')
      } else {
        // 钱包余额支付
        if (this.model.paymentType === '3') {
          this.showWalletPay = true
          this.walletPwd = ''
        } else {
          // 在线支付
          const newTab = window.open('/static/pay.html')
          // let _this = this
          this.$refs.form.validate().then((result) => {
            if (result) {
              this.btnLoading = true
              let couponsOrderBeans = []
              this.tableData.forEach(v => {
                if (v.couponsId) {
                  couponsOrderBeans.push({orderId: v.id, couponsId: v.couponsId})
                }
              })
              this.$ajax.post('/ms-fahuobao-payment/FhbPay/MergerOrderPay', {
                merOrderIdList: this.ids,
                payType: this.model.paymentType,
                couponsOrderBeans: couponsOrderBeans
              }).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  let temp = `<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                </head>
                <body>
                ${response.data.sHtmlText}
                </body>
                </html>
                `
                  newTab.document.write(temp)
                  newTab.focus()
                  this.payDialog = true
                  this.disabledBtn = false
                } else {
                  newTab.close()
                  this.unsuccessful()
                }
              }).catch(() => {
                newTab.close()
                this.unsuccessful()
              })
            }
          })
        }
      }
    },
    // 余额支付
    walletpay() {
      this.loading = true
      let couponsOrderBeans = []
      this.tableData.forEach(v => {
        if (v.couponsId) {
          couponsOrderBeans.push({orderId: v.id, couponsId: v.couponsId})
        }
      })
      this.$ajax.post('/ms-user-wallet/wallet/balance-pay', {
        objectList: this.ids,
        money: this.lastMoney,
        password: this.walletPwd,
        couponsOrderBeans: couponsOrderBeans
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          confirm('支付成功', '提示', {
            type: 'success'
          }).finally(_ => {
            this.btnDialog() // 刷新页面到父页面
          })
          this.showWalletPay = false
          this.walletPwd = ''
        } else {
          this.error_message = dotData(response, 'error')
        }
        this.loading = false
      })
    },
    pwdChange(value) {
      console.log('change')
      this.error_message = ''
    },
    // 在线支付
    goPay() {
      this.$nextTick(_ => {
        document.getElementById('submit').submit()
        this.payDialog = true
        this.disabledBtn = false
      })
    },
    successful() {
      // this.disabledBtn = true
      let orderParam = {
        list: this.ids
      }
      this.$ajax.post('/ms-fahuobao-json-view/FhbOrder/finByOrderPayStatus', orderParam).then(response => {
        const success = dotData(response, 'data')
        if (success) {
          this.paymentState = true
          this.payDialog = false
          setTimeout(() => {
            this.btnDialog() // 刷新页面到父页面
          }, 3000)
        } else {
          /*
          if (this.payDialog) {
            setTimeout(() => {
              if (this.timer > 0) {
                this.timer--
                this.successful()
              } else {
                this.payDialog = false
                swal({
                  title: '支付失败,跳转至列表',
                  confirmButtonText: '确定 ',
                  type: 'warning',
                  customClass: 'visible'
                }, (confirm) => {
                  this.btnDialog() // 刷新页面到父页面
                })
              }
            }, 1000)
          }
          */
          this.disabledBtn = true
        }
      })
    },
    btnDialog() {
      this.paymentState = false
      // this.setCloseRoute({path: this.$route.fullPath})
      // this.setRefreshRoute({path: '/ss-fhb/myOrders/pending/index'})
      this.$router.push({path: '/redirect/ss-fhb/myOrders/pending/index'})
    },
    unsuccessful() {
      this.payDialog = false
      this.$confirm('很抱歉！支付失败。您可以尝试重新支付或联系客服。', '温馨提示', {
        confirmButtonText: '重新支付',
        cancelButtonText: '联系客服',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      }).then(() => {
        // 重新支付
        // this.goPay()
        this.payment()
      }).catch(() => {
        // 联系客服
        this.btnLoading = false
      })
    },
    getfhbCouponsDisable(arr) {
      let usedId = this.usedArr
      let temp = copy(arr, true)
      return temp.map(v => {
        if (usedId.indexOf(v.id) >= 0) {
          v.disabled = true
        }
        return v
      })
    }
  }
}
</script>
